<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.6" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.6">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.6">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.6">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.6" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.6',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  

<meta name="description" content="可读性的重要性 用名字表达代码含义 名字不能带来歧义 良好的代码风格 编写注释 如何编写注释 提高控制流的可读性 拆分长表达式 变量与可读性 抽取函数 一次只做一件事 用自然语言表述代码 减少代码量   可读性的重要性编程有很大一部分时间是在阅读代码，不仅要阅读自己的代码，而且要阅读别人的代码。因此，可读性良好的代码能够大大提高编程效率。 可读性良好的代码往往会让代码架构更好，因为程序员更愿意">
<meta name="keywords" content="代码规范">
<meta property="og:type" content="article">
<meta property="og:title" content="代码可读性（转）">
<meta property="og:url" content="http://7ht.gitee.io/2018/03/16/代码可读性（转）/index.html">
<meta property="og:site_name" content="HonTu&#39;s Notes">
<meta property="og:description" content="可读性的重要性 用名字表达代码含义 名字不能带来歧义 良好的代码风格 编写注释 如何编写注释 提高控制流的可读性 拆分长表达式 变量与可读性 抽取函数 一次只做一件事 用自然语言表述代码 减少代码量   可读性的重要性编程有很大一部分时间是在阅读代码，不仅要阅读自己的代码，而且要阅读别人的代码。因此，可读性良好的代码能够大大提高编程效率。 可读性良好的代码往往会让代码架构更好，因为程序员更愿意">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-03-28T03:26:50.165Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="代码可读性（转）">
<meta name="twitter:description" content="可读性的重要性 用名字表达代码含义 名字不能带来歧义 良好的代码风格 编写注释 如何编写注释 提高控制流的可读性 拆分长表达式 变量与可读性 抽取函数 一次只做一件事 用自然语言表述代码 减少代码量   可读性的重要性编程有很大一部分时间是在阅读代码，不仅要阅读自己的代码，而且要阅读别人的代码。因此，可读性良好的代码能够大大提高编程效率。 可读性良好的代码往往会让代码架构更好，因为程序员更愿意">






  <link rel="canonical" href="http://7ht.gitee.io/2018/03/16/代码可读性（转）/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>代码可读性（转） | HonTu's Notes</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> 

<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HonTu's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一小瓶</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        
          
  <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      

      
    </ul>
  

  

  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://7ht.gitee.io/2018/03/16/代码可读性（转）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Q.hongtao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/head_cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HonTu's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">代码可读性（转）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-16T19:23:11+08:00">2018-03-16</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/基础知识/" itemprop="url" rel="index"><span itemprop="name">基础知识</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <!-- GFM-TOC -->
<ul>
<li><a href="#可读性的重要性">可读性的重要性</a></li>
<li><a href="#用名字表达代码含义">用名字表达代码含义</a></li>
<li><a href="#名字不能带来歧义">名字不能带来歧义</a></li>
<li><a href="#良好的代码风格">良好的代码风格</a></li>
<li><a href="#编写注释">编写注释</a></li>
<li><a href="#如何编写注释">如何编写注释</a></li>
<li><a href="#提高控制流的可读性">提高控制流的可读性</a></li>
<li><a href="#拆分长表达式">拆分长表达式</a></li>
<li><a href="#变量与可读性">变量与可读性</a></li>
<li><a href="#抽取函数">抽取函数</a></li>
<li><a href="#一次只做一件事">一次只做一件事</a></li>
<li><a href="#用自然语言表述代码">用自然语言表述代码</a></li>
<li><a href="#减少代码量">减少代码量</a><!-- GFM-TOC -->
</li>
</ul>
<h1 id="可读性的重要性"><a href="#可读性的重要性" class="headerlink" title="可读性的重要性"></a>可读性的重要性</h1><p>编程有很大一部分时间是在阅读代码，不仅要阅读自己的代码，而且要阅读别人的代码。因此，可读性良好的代码能够大大提高编程效率。</p>
<p>可读性良好的代码往往会让代码架构更好，因为程序员更愿意去修改这部分代码，而且也更容易修改。</p>
<p>只有在核心领域为了效率才可以放弃可读性，否则可读性是第一位。</p>
<h1 id="用名字表达代码含义"><a href="#用名字表达代码含义" class="headerlink" title="用名字表达代码含义"></a>用名字表达代码含义</h1><p>一些比较有表达力的单词：</p>
<table>
<thead>
<tr>
<th>单词</th>
<th>可替代单词</th>
</tr>
</thead>
<tbody>
<tr>
<td>send</td>
<td>deliver、dispatch、announce、distribute、route</td>
</tr>
<tr>
<td>find</td>
<td>search、extract、locate、recover</td>
</tr>
<tr>
<td>start</td>
<td>launch、create、begin、open</td>
</tr>
<tr>
<td>make</td>
<td>create、set up、build、generate、compose、add、new</td>
</tr>
</tbody>
</table>
<p>使用 i、j、k 作为循环迭代器的名字过于简单，user_i、member_i 这种名字会更有表达力。因为循环层次越多，代码越难理解，有表达力的迭代器名字可读性会更高</p>
<p>为名字添加形容词等信息能让名字更具有表达力，但是名字也会变长。名字长短的准则是：作用域越大，名字越长。因此只有在短作用域才能使用一些简单名字。</p>
<h1 id="名字不能带来歧义"><a href="#名字不能带来歧义" class="headerlink" title="名字不能带来歧义"></a>名字不能带来歧义</h1><p>起完名字要思考一下别人会对这个名字有何解读，会不会误解了原本想表达的含义。</p>
<p>用 min、max 表示数量范围；用 first、last 表示访问空间的包含范围，begin、end 表示访问空间的排除范围，即 end 不包含尾部。</p>
<p>布尔相关的命名加上 is、can、should、has 等前缀。</p>
<h1 id="良好的代码风格"><a href="#良好的代码风格" class="headerlink" title="良好的代码风格"></a>良好的代码风格</h1><p>适当的空行和缩进。</p>
<p>排列整齐的注释：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">int a = 1;   // 注释</span><br><span class="line">int b = 11;  // 注释</span><br><span class="line">int c = 111; // 注释</span><br></pre></td></tr></table></figure>
<p>语句顺序不能随意，比如与 html 表单相关联的变量的赋值应该和表单在 html 中的顺序一致；</p>
<p>把相关的代码按块组织起来放在一起。</p>
<h1 id="编写注释"><a href="#编写注释" class="headerlink" title="编写注释"></a>编写注释</h1><p>阅读代码首先会注意到注释，如果注释没太大作用，那么就会浪费代码阅读的时间。那些能直接看出含义的代码不需要写注释，特别是并不需要为每个方法都加上注释，比如那些简单的 getter 和 setter 方法，为这些方法写注释反而让代码可读性更差。</p>
<p>不能因为有注释就随便起个名字，而是争取起个好名字而不写注释。</p>
<p>可以用注释来记录采用当前解决办法的思考过程，从而让读者更容易理解代码。</p>
<p>注释用来提醒一些特殊情况。</p>
<p>用 TODO 等做标记：</p>
<table>
<thead>
<tr>
<th>标记</th>
<th>用法</th>
</tr>
</thead>
<tbody>
<tr>
<td>TODO</td>
<td>待做</td>
</tr>
<tr>
<td>FIXME</td>
<td>待修复</td>
</tr>
<tr>
<td>HACH</td>
<td>粗糙的解决方案</td>
</tr>
<tr>
<td>XXX</td>
<td>危险！这里有重要的问题</td>
</tr>
</tbody>
</table>
<h1 id="如何编写注释"><a href="#如何编写注释" class="headerlink" title="如何编写注释"></a>如何编写注释</h1><p>尽量简洁明了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">// The first String is student&apos;s name</span><br><span class="line">// The Second Integer is student&apos;s score</span><br><span class="line">Map&lt;String, Integer&gt; scoreMap = new HashMap&lt;&gt;();</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// Student&apos; name -&gt; Student&apos;s score</span><br><span class="line">Map&lt;String, Integer&gt; scoreMap = new HashMap&lt;&gt;();</span><br></pre></td></tr></table></figure>
<p>添加测试用例来说明：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">//...</span><br><span class="line">// Example: add(1, 2), return 3</span><br><span class="line">int add(int x, int y) &#123;</span><br><span class="line">    return x + y;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在很复杂的函数调用中对每个参数标上名字：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">int a = 1;</span><br><span class="line">int b = 2;</span><br><span class="line">int num = add(\* x = *\ a, \* y = *\ b);</span><br></pre></td></tr></table></figure>
<p>使用专业名词来缩短概念上的解释，比如用设计模式名来说明代码。</p>
<h1 id="提高控制流的可读性"><a href="#提高控制流的可读性" class="headerlink" title="提高控制流的可读性"></a>提高控制流的可读性</h1><p>条件表达式中，左侧是变量，右侧是常数。比如下面第一个语句正确：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if(len &lt; 10)</span><br><span class="line">if(10 &gt; len)</span><br></pre></td></tr></table></figure>
<p>if / else 条件语句，逻辑的处理顺序为：① 正逻辑；② 关键逻辑；③ 简单逻辑。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">if(a == b) &#123;</span><br><span class="line">    // 正逻辑</span><br><span class="line">&#125; else&#123;</span><br><span class="line">    // 反逻辑</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>只有在逻辑简单的情况下使用 ? : 三目运算符来使代码更紧凑，否则应该拆分成 if / else；</p>
<p>do / while 的条件放在后面，不够简单明了，并且会有一些迷惑的地方，最好使用 while 来代替。</p>
<p>如果只有一个 goto 目标，那么 goto 尚且还能接受，但是过于复杂的 goto 会让代码可读性特别差，应该避免使用 goto。</p>
<p>在嵌套的循环中，用一些 return 语句往往能减少嵌套的层数。</p>
<h1 id="拆分长表达式"><a href="#拆分长表达式" class="headerlink" title="拆分长表达式"></a>拆分长表达式</h1><p>长表达式的可读性很差，可以引入一些解释变量从而拆分表达式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if line.split(&apos;:&apos;)[0].strip() == &quot;root&quot;:</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">username = line.split(&apos;:&apos;)[0].strip()</span><br><span class="line">if username == &quot;root&quot;:</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<p>使用摩根定理简化一些逻辑表达式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if(!a &amp;&amp; !b) &#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if(a || b) &#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="变量与可读性"><a href="#变量与可读性" class="headerlink" title="变量与可读性"></a>变量与可读性</h1><p><strong>去除控制流变量</strong> 。在循环中通过使用 break 或者 return 可以减少控制流变量的使用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">boolean done = false;</span><br><span class="line">while(/* condition */ &amp;&amp; !done) &#123;</span><br><span class="line">    ...</span><br><span class="line">    if(...) &#123;</span><br><span class="line">        done = true;</span><br><span class="line">        continue;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">while(/* condition */) &#123;</span><br><span class="line">    ...</span><br><span class="line">    if(...) &#123;</span><br><span class="line">        break;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>减小变量作用域</strong> 。作用域越小，越容易定位到变量所有使用的地方。</p>
<p>JavaScript 可以用闭包减小作用域。以下代码中 submit_form 是函数变量，submitted 变量控制函数不会被提交两次。第一个实现中 submitted 是全局变量，第二个实现把 submitted 放到匿名函数中，从而限制了起作用域范围。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">submitted = false;</span><br><span class="line">var submit_form = function(form_name) &#123;</span><br><span class="line">    if(submitted) &#123;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    submitted = true;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var submit_form = (function() &#123;</span><br><span class="line">    var submitted = false;</span><br><span class="line">    return function(form_name) &#123;</span><br><span class="line">        if(submitted) &#123;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        submitted = true;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;());  // () 使得外层匿名函数立即执行</span><br></pre></td></tr></table></figure>
<p>JavaScript 中没有用 var 声明的变量都是全局变量，而全局变量很容易造成迷惑，因此应当总是用 var 来声明变量。</p>
<p>变量定义的位置应当离它使用的位置最近。</p>
<p><strong>实例解析</strong></p>
<p>在一个网页中有以下文本输入字段：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = &quot;text&quot; id = &quot;input1&quot; value = &quot;a&quot;&gt;</span><br><span class="line">&lt;input type = &quot;text&quot; id = &quot;input2&quot; value = &quot;b&quot;&gt;</span><br><span class="line">&lt;input type = &quot;text&quot; id = &quot;input3&quot; value = &quot;&quot;&gt;</span><br><span class="line">&lt;input type = &quot;text&quot; id = &quot;input4&quot; value = &quot;d&quot;&gt;</span><br></pre></td></tr></table></figure>
<p>现在要接受一个字符串并把它放到第一个空的 input 字段中，初始实现如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var setFirstEmptyInput = function(new_alue) &#123;</span><br><span class="line">    var found = false;</span><br><span class="line">    var i = 1;</span><br><span class="line">    var elem = document.getElementById(&apos;input&apos; + i);</span><br><span class="line">    while(elem != null) &#123;</span><br><span class="line">        if(elem.value === &apos;&apos;) &#123;</span><br><span class="line">            found = true;</span><br><span class="line">            break;</span><br><span class="line">        &#125;</span><br><span class="line">        i++;</span><br><span class="line">        elem = document.getElementById(&apos;input&apos; + i);</span><br><span class="line">    &#125;</span><br><span class="line">    if(found) elem.value = new_value;</span><br><span class="line">    return elem;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上实现有以下问题：</p>
<ul>
<li>found 可以去除；</li>
<li>elem 作用域过大；</li>
<li>可以用 for 循环代替 while 循环；</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">var setFirstEmptyInput = function(new_value) &#123;</span><br><span class="line">    for(var i = 1; true; i++) &#123;</span><br><span class="line">        var elem = document.getElementById(&apos;input&apos; + i);</span><br><span class="line">        if(elem === null) &#123;</span><br><span class="line">            return null;</span><br><span class="line">        &#125;</span><br><span class="line">        if(elem.value === &apos;&apos;) &#123;</span><br><span class="line">            elem.value = new_value;</span><br><span class="line">            return elem;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h1 id="抽取函数"><a href="#抽取函数" class="headerlink" title="抽取函数"></a>抽取函数</h1><p>工程学就是把大问题拆分成小问题再把这些问题的解决方案放回一起。</p>
<p>首先应该明确一个函数的高层次目标，然后对于不是直接为了这个目标工作的代码，抽取出来放到独立的函数中。</p>
<p>介绍性的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">int findClostElement(int[] arr) &#123;</span><br><span class="line">    int clostIdx;</span><br><span class="line">    int clostDist = Interger.MAX_VALUE;</span><br><span class="line">    for(int i = 0; i &lt; arr.length; i++) &#123;</span><br><span class="line">        int x = ...;</span><br><span class="line">        int y = ...;</span><br><span class="line">        int z = ...;</span><br><span class="line">        int value = x * y * z;</span><br><span class="line">        int dist = Math.sqrt(Math.pow(value, 2), Math.pow(arr[i], 2));</span><br><span class="line">        if(dist &lt; clostDist) &#123;</span><br><span class="line">            clostIdx = i;</span><br><span class="line">            clostDist = value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return clostIdx;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上代码中循环部分主要计算距离，这部分不属于代码高层次目标，高层次目标是寻找最小距离的值，因此可以把这部分代替提取到独立的函数中。这样做也带来一个额外的好处有：可以单独进行测试、可以快速找到程序错误并修改。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public int findClostElement(int[] arr) &#123;</span><br><span class="line">    int clostIdx;</span><br><span class="line">    int clostDist = Interger.MAX_VALUE;</span><br><span class="line">    for(int i = 0; i &lt; arr.length; i++) &#123;</span><br><span class="line">        int dist = computDist(arr, i);</span><br><span class="line">        if(dist &lt; clostDist) &#123;</span><br><span class="line">            clostIdx = i;</span><br><span class="line">            clostDist = value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return clostIdx;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>并不是函数抽取的越多越好，如果抽取过多，在阅读代码的时候可能需要不断跳来跳去。只有在当前函数不需要去了解某一块代码细节而能够表达其内容时，把这块代码抽取成子函数才是好的。</p>
<p>函数抽取也用于减小代码的冗余。</p>
<h1 id="一次只做一件事"><a href="#一次只做一件事" class="headerlink" title="一次只做一件事"></a>一次只做一件事</h1><p>只做一件事的代码很容易让人知道其要做的事；</p>
<p>基本流程：列出代码所做的所有任务；把每个任务拆分到不同的函数，或者不同的段落。</p>
<h1 id="用自然语言表述代码"><a href="#用自然语言表述代码" class="headerlink" title="用自然语言表述代码"></a>用自然语言表述代码</h1><p>先用自然语言书写代码逻辑，也就是伪代码，然后再写代码，这样代码逻辑会更清晰。</p>
<h1 id="减少代码量"><a href="#减少代码量" class="headerlink" title="减少代码量"></a>减少代码量</h1><p>不要过度设计，编码过程会有很多变化，过度设计的内容到最后往往是无用的。</p>
<p>多用标准库实现。</p>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><ul>
<li>转载自<a href="https://github.com/CyC2018" target="_blank" rel="noopener">https://github.com/CyC2018</a></li>
</ul>

      
    </div>

    

    
    
    

    <div>
          
            

          
      </div>

    

    

    
  <div>
  
    

  
</div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/代码规范/" rel="tag"># 代码规范</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/16/GIT（转）/" rel="next" title="GIT（转）">
                <i class="fa fa-chevron-left"></i> GIT（转）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/17/个人总结/" rel="prev" title="个人总结">
                个人总结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/head_cat.jpg"
                alt="Q.hongtao" />
            
              <p class="site-author-name" itemprop="name">Q.hongtao</p>
              <p class="site-description motion-element" itemprop="description">没有可怕的深度 就没有美丽的水面</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">34</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/ht-dep" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:15662728521@163.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#可读性的重要性"><span class="nav-number">1.</span> <span class="nav-text">可读性的重要性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#用名字表达代码含义"><span class="nav-number">2.</span> <span class="nav-text">用名字表达代码含义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#名字不能带来歧义"><span class="nav-number">3.</span> <span class="nav-text">名字不能带来歧义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#良好的代码风格"><span class="nav-number">4.</span> <span class="nav-text">良好的代码风格</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编写注释"><span class="nav-number">5.</span> <span class="nav-text">编写注释</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#如何编写注释"><span class="nav-number">6.</span> <span class="nav-text">如何编写注释</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#提高控制流的可读性"><span class="nav-number">7.</span> <span class="nav-text">提高控制流的可读性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#拆分长表达式"><span class="nav-number">8.</span> <span class="nav-text">拆分长表达式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#变量与可读性"><span class="nav-number">9.</span> <span class="nav-text">变量与可读性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#抽取函数"><span class="nav-number">10.</span> <span class="nav-text">抽取函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#一次只做一件事"><span class="nav-number">11.</span> <span class="nav-text">一次只做一件事</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#用自然语言表述代码"><span class="nav-number">12.</span> <span class="nav-text">用自然语言表述代码</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#减少代码量"><span class="nav-number">13.</span> <span class="nav-text">减少代码量</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考资料"><span class="nav-number">14.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ht-dep</span>

  

  
</div>



















        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.6"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.6"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.6"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.6"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.6"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.6"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.6"></script>



  



	





  





  










  





  

  

  

  

  
  

  

  

  

  


<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"display":{"position":"right","width":100,"height":150},"model":{"jsonPath":"/live2dw/assets/tororo.model.json"},"mobile":{"show":false,"scale":0.5},"react":{"opacityDefault":1,"opacityOnHover":0.2}});</script></body>
</html>
